//
//  OauthViewController.swift
//  XLWB
//
//  Created by 郭亮 on 16/3/16.
//  Copyright © 2016年 gl. All rights reserved.
//

import UIKit
import SVProgressHUD

class OauthViewController: UIViewController {
    
    // MARK:-属性
    private var accessToken: AccessTokenItem?

    @IBOutlet weak var webView: UIWebView!
    
    // MARK:-系统回调方法
    override func viewDidLoad() {
        super.viewDidLoad()

        //设置导航栏
        setupNavigationBar()
        
        //加载页面
        loadPage()
    }
}

// MARK:-UI界面
extension OauthViewController {
    private func setupNavigationBar() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充", style: .Plain, target: self, action: "fill")
        
        title = "登录页面"
    }
    
    private func loadPage() {

        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(app_key)&redirect_uri=\(redirect_uri)"
        
        guard let url = NSURL(string: urlString) else {
        return
        }
        
        let request = NSURLRequest(URL: url)
        
        webView.loadRequest(request)
    }
    
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
        SVProgressHUD.dismiss()
    }
    
    @objc private func fill() {
        // 1.获取要执行的js(JavaScript)代码
        let jsCode = "document.getElementById('userId').value='1606020376@qq.com';document.getElementById('passwd').value='haomage';"
        
        // 2.webView执行js代码
        webView.stringByEvaluatingJavaScriptFromString(jsCode)
    }
}

// MARK:-UIWebViewDelegate
extension OauthViewController: UIWebViewDelegate {
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //拿到加载页面的urlString
        guard let urlString = request.URL?.absoluteString else {
        return true
        }
        
        //如果有,判断是否包含code
        if urlString.containsString("code=") {
            guard let code = urlString.componentsSeparatedByString("code=").last else {
            return true
            }
            
            //换取accessToken
            loadAccessToken(code)
            return false
        }
        
        return true
    }
}


extension OauthViewController {
    ///加载accessToken
    private func loadAccessToken(code: String) {
        
        //创建urlString
        let urlstring = "https://api.weibo.com/oauth2/access_token"
        
        //参数设置
        let parameters = ["client_id": app_key, "client_secret": app_secret, "grant_type": "authorization_code", "code": code, "redirect_uri": redirect_uri]
        
        NetworkingTolls.shareInstance.request(.RequestStylePost, urlString: urlstring, parameters: parameters) { (result, error) -> () in
            if result != nil {
                //字典转模型
                let dict = result as! [String: AnyObject]
                self.accessToken = AccessTokenItem(dict: dict)
                //获取用户信息
                self.loadUserInfo()
        }else {
            print(error!)
        }
        }
    }
}

extension OauthViewController {
    ///加载用户信息
    private func loadUserInfo() {
        
        //创建urlString
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        //设置参数
        guard let accessToken = accessToken?.access_token, uid = self.accessToken?.uid else {
        return
        }
        let parameters = ["access_token": accessToken, "uid": uid]
        
        //发送请求
        NetworkingTolls.shareInstance.request(.RequestStyleGet, urlString: urlString, parameters: parameters) { (result, error) -> () in
            if result != nil {
                let result = result as! [String: AnyObject]
                self.accessToken?.screen_name = result["screen_name"] as? String
                self.accessToken?.avatar_large = result["avatar_large"] as? String
                //保存accessToken对象
                NSKeyedArchiver.archiveRootObject(self.accessToken!, toFile: caches_AccessToken)
                //给viewModal里面的模型属性赋值
                UserAccountViewModal.shareInstance.accessToken = self.accessToken
                //销毁Oauth控制器,并跳转到欢迎界面
                self.dismissViewControllerAnimated(false, completion: { () -> Void in
                   UIApplication.sharedApplication().keyWindow?.rootViewController? = WelcomeViewController()
                })
            }else {
            print(error!)
            }
        }
    }
}






